package com.frejoys.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.admin.DelIdDto;
import com.frejoys.common.dto.common.auth.AuthGroupAddDto;
import com.frejoys.common.dto.common.auth.AuthGroupAuthorizeDto;
import com.frejoys.common.dto.common.auth.AuthGroupListDto;
import com.frejoys.common.dto.common.auth.AuthGroupUpDto;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.admin.AuthGroupVo;
import com.frejoys.dao.entity.AuthGroup;
import com.frejoys.service.AuthGroupService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "权限组", description = "权限组(角色)管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixAdmin)
@Authorization(Authority.Private)
public class AdminAuthGroupController {

    private final AuthGroupService authGroupService;

    private final RedissonClient redissonClient;

    @Operation(summary = "创建权限组")
    @PostMapping("/auth/group/addInfo")
    public Result authRuleAddInfo(@RequestBody @Validated AuthGroupAddDto dto) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.addAuthGroupLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                authGroupService.addInfo(dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    @Operation(summary = "修改权限组")
    @PostMapping("/auth/group/upInfo")
    public Result authRuleUpInfo(@RequestBody @Validated AuthGroupUpDto dto) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.upAuthGroupLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                authGroupService.upInfo(dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    @Operation(summary = "权限组列表")
    @PostMapping("/auth/group/list")
    public Result<IPage<AuthGroupVo>> authRuleList(@RequestBody @Validated AuthGroupListDto dto) {
        IPage<AuthGroup> authGroups = authGroupService.listInfo(RequestUtil.userId(), dto);
        IPage<AuthGroupVo> authGroupVos = authGroups.convert(authGroup -> BeanUtil.copyProperties(authGroup, AuthGroupVo.class));
        return Result.success(authGroupVos);
    }


    @Operation(summary = "分配权限给用户")
    @PostMapping("/auth/group/authorize")
    public Result authRuleAuthorize(@RequestBody @Validated AuthGroupAuthorizeDto dto) {
        authGroupService.authRuleAuthorize(dto);
        return Result.success();
    }

    @Operation(summary = "删除权限组")
    @PostMapping("/auth/group/delete")
    public Result deleteAuthRule(@RequestBody @Validated DelIdDto dto) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.upAuthGroupLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                authGroupService.deleteAuthRule(dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }
}
